package com.example.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * GlobalFilter 全局
 * @author hmy
 */
//@Component
public class GlobalTokenFilter implements GlobalFilter, Ordered {
    private static final List<String> EXIST_TOKEN_LIST = new ArrayList<String>();

    static {
        EXIST_TOKEN_LIST.add("token1");
        EXIST_TOKEN_LIST.add("token2");
        EXIST_TOKEN_LIST.add("token3");
        EXIST_TOKEN_LIST.add("token4");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("开始校验权限");
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        List<String> tokens = queryParams.get("token");
        String token = tokens == null ? null : tokens.get(0);
        if (token != null && EXIST_TOKEN_LIST.contains(token)) {
            // 继续执行 这里暂时无法向请求中设置参数；如: req.setAttribute("userId",  u.getUserId());
            return chain.filter(exchange);
        }else{
            // 返回未登录得提示信息
            return exchange.getResponse().writeWith(Flux.just(exchange.getResponse()
                    .bufferFactory().wrap("没有登陆".getBytes())));
        }


    }

    @Override
    public int getOrder() {
        return 1;
    }
}
